<template>
  <div>
    <BasicTable @register="registerTable" ref="tableRef">
      <template #toolbar>
        <Button type="primary" @click="handleCreate"> 新增商品 </Button>
        <Button type="primary" @click="showUpConfirm"> 批量启用 </Button>
        <Button danger @click="showDownConfirm"> 批量停用 </Button>
        <!--        style="margin-right: 10px"-->
        <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
          <Button class="m-3" :loading="loading"> 导入Excel </Button>
        </ImpExcel>
        <!--        <Button type="primary" @click="handleCreate" > excel导入 </Button>-->
        <Button @click="aoaToExcel"> 模版下载 </Button>
        <Button type="primary" @click="addStoreProductFn"> 增加库存 </Button>

      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '删除数据将无法恢复是否继续?',
                placement: 'left',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]" />
        </template>
        <template v-else-if="column.key === 'pic'">
          <Image :height="50" :src="record.pic" />
        </template>
      </template>
    </BasicTable>
    <FormModal @register="register" @success="handleSuccess" />
    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>
    <AddFormModal @register="userModal[0]" @success="handleSuccess"></AddFormModal>

  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction, TableImg } from '@/components/Table';
import { productListApi, productDownApi, productUpApi, productStockApi, productDeleteApi, productDownQueryApi } from '@/api/sys/wmProduct';
import FormModal from './FormModal.vue';
import { ref, watch, onMounted, createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { columns, searchFormSchema } from './role.data';
import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Image, Button, Modal } from 'ant-design-vue';
import { aoaToSheetXlsx, ImpExcel } from '@/components/Excel';
import AddFormModal from './AddFormModal.vue';

import util from "@/utils/util";
import { inStorageApi } from "@/api/sys/wmStorage";
import { excelColumns } from "@/views/store/inStorage/role.data";

defineOptions({ name: 'goodList' });
const { createMessage } = useMessage();
const [register, { openModal, closeModal }] = useModal();
const [registerTable, { reload, clearSelectedRowKeys }] = useTable({
  title: '商品列表',
  api: productListApi,
  size: "small",
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    submitOnChange: function (p) {
      // console.log("--改变了:",p)
    },
    autoSubmitOnEnter: true,
  },
  pagination: {
    pageSize: 50,
  },
  useSearchForm: true,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  rowSelection: {
    type: 'checkbox',
  },
  rowKey: 'id',

  actionColumn: {
    width: 80,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
    fixed: undefined,
  },
});
const tableRef = ref();

const formData = ref({});
const loading = ref(false);
const userModal = useModal();

function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}

function handleDelete(record: Recordable) {
  //console.log(record);
  productStockApi({ prodId: record.id }).then((res) => {
    if (res.code == 200) {
      console.log("--data:", res.data)
      let is_error = false;
      let content = "";
      if (res.data.stock > 0 || res.data.goodNames) {
        is_error = true;
        if (res.data.stock > 0) {
          content += "库存：" + res.data.stock + "\n";
        }
        if (res.data.goodNames) {
          content += "微信商城该商品还在上架状态：" + res.data.goodNames;
        }
      }
      if (is_error) {
        Modal.confirm({
          title: () => '该商品存在以下信息，请确认是否继续删除',
          icon: () => createVNode(ExclamationCircleOutlined),
          content: () => content,
          okText: () => '确定',
          okType: 'danger',
          cancelText: () => '取消',
          onOk() {
            productDeleteApi(record)
              .then((res) => {
                createMessage.success(res.message);
              })
              .catch((res) => {
                createMessage.error(res.message);
              })
              .finally(() => {
                reload();
              });
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      } else {
        productDeleteApi(record)
          .then((res) => {
            createMessage.success(res.message);
          })
          .catch((res) => {
            createMessage.error(res.message);
          })
          .finally(() => {
            reload();
          });
      }
    }
  })


}


const showUpConfirm = () => {
  let keys = tableRef.value.getSelectRowKeys();

  Modal.confirm({
    title: () => '提示信息',
    icon: () => createVNode(ExclamationCircleOutlined),
    content: () => createVNode('div', { style: 'color:green;' }, '确定启用这些商品?'),
    okText: () => '确定',
    cancelText: () => '取消',
    onOk() {
      batchUpFn(keys)
    },
    onCancel() {
      // console.log('Cancel');
    },
    class: 'test',
  });
};
const showDownConfirm = () => {
  let keys = tableRef.value.getSelectRowKeys();
  if (util.isEmpty(keys)) {
    createMessage.error("请先勾选商品");
    return false;
  }
  Modal.confirm({
    title: () => '提示信息',
    icon: () => createVNode(ExclamationCircleOutlined),
    content: () => '是否停用这些商品',
    okText: () => '确定',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      queryDownProInfo(keys)
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

/**
 * 查询这些产品有没有在商城中上架
 * @param key
 */
function queryDownProInfo(keys) {
  productDownQueryApi({ ids: keys.join(",") }).then(res => {
    if (res.code == 200) {
      if (res.data && res.data.goodNames) {
        let txt = "";
        let divArr = [
          createVNode('p', { style: 'color:red;font-size:18px;' }, "以下商品已在微信商城中上架是否继续，继续停用将会将这些商品同步下架？")
        ];
        res.data.goodNames.forEach(r => {
          divArr.push(createVNode('p', { style: 'color:gray' }, r),)
        })
        const divVNode = createVNode('div', {}, divArr);
        Modal.confirm({
          title: () => '提示信息',
          icon: () => createVNode(ExclamationCircleOutlined),
          content: () => divVNode,
          okText: () => '确定停用',
          okType: 'danger',
          cancelText: () => '取消',
          onOk() {
            batchDownFn(keys)
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      }

    }
  })
}


function batchUpFn(keys) {
  productUpApi({ ids: keys.join(",") }).then(res => {
    if (res.code == 200) {
      createMessage.success("启用成功!")
      reload();
    } else {
      createMessage.error(res.message)
    }
  })

}

function batchDownFn(keys) {
  productDownApi({ ids: keys.join(",") }).then(res => {
    if (res.code == 200) {
      createMessage.success("停用成功!")
      reload();
    } else {
      createMessage.error(res.message)
    }
  })
}

function handleSuccess() {
  reload();
}

function aoaToExcel() {
  window.open('http://www.jiezuowenhua.com.cn/app_file/excel/商品导入模版.xls');
}


let arrHeader = [];
function getHeadArr() {
  let arr = [];
  arrHeader.forEach((r) => {
    arr.push(r.value);
  });
  return arr;
}

function changeSubmitArr(results) {
  let data = {
    list: [],
  };
  let list = [];
  // console.log("--results:",results)
  results.forEach((r) => {
    let json = {};
    for (let key in r) {
      excelColumns.forEach((e) => {
        if (e.excel_title == key) {
          let value = r[key];
          if (value) {
            try {
              value = value + "".split(" ").join("");
            } catch (e) {
              console.log(e)
            }
          }
          json[e.field] = value;
        }
      });
    }
    data.list.push(json);
  });
  return data;
}

const msgList = ref([]);
const visible = ref(false);

function excelSuccessFn(list) {
  let results = list[0].results;
  // console.log(results);
  //去除第一行文字提示 shift 删除前两行
  results.shift();

  let data = changeSubmitArr(results);
  // console.log(data);

  formData.value.list = data.list;
  // console.log("----formData.value::",formData.value);
  loading.value = true;
  inStorageApi(formData.value)
    .then((res) => {
      loading.value = false;

      if (res.code == 200) {
        if (res.data && res.data.length > 0) {
          let msg = "";
          for (let i = 0; i < res.data.length; i++) {
            let row = res.data[i];
            msg += `第${row.index}行 ${row.message}\n`
          }
          msgList.value = res.data;
          visible.value = true;
        } else {
          createMessage.success('导入成功!');
          closeFn();
        }
      } else {
        loading.value = false;

        createMessage.error(res.message);
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}

function handleOk() {
  visible.value = false;
}



function addStoreProductFn() {
  // openModal(true, {
  //   isUpdate: false,
  // });
  openUserModal()
}

function openUserModal() {
  userModal[1].openModal(true, {
    isUpdate: false

  });
}

</script>
